import Vue from "vue";
import axios from "axios";
import throttle from "lodash/throttle";
import loading from "../components/common/loadding-index";
import Cookie from "../utils/cookie";
import { message } from "ant-design-vue";
//全局默认配置
let loaddingNumber = 0; // 记录请求次数
const instance = axios.create({
  baseURL: "", // process.env.NODE_ENV == "production" ? conf.proBaseURL : conf.devBaseURL,
  // timeout: 30000, // 请求超时时间
  headers: {
    "X-Requested-With": "XMLHttpRequest",
    "content-type": "application/json",
  },
  withCredentials: false,
});
instance.defaults.retry = 4; // 全局的请求次数
instance.defaults.retryDelay = 1000; // 全局的请求的间隙
instance.defaults.headers.post["Content-Type"] =
  "application/json;charset=UTF-8";
let messageInstance = null;
/*const message = (type = "info", message = "加载中...", duration = 2) => {
  if (!messageInstance) {
    messageInstance = Vue.prototype.$message;
  }
  messageInstance[type](message, duration);
};*/
// const resetMessage = throttle(message, 1000);
// 增加重试 TODO后端配合模拟场景验证
const retryConnect = (obj) => {
  let config = obj.config; // 获取错误信息
  if (!config || !config.retry) return Promise.reject(obj);
  config.__retryCount = config.__retryCount || 0;
  if (config.__retryCount >= config.retry) {
    // console.log("网络连接失败...");
    // Vue.prototype.$Toast.clear(); // 隐藏loading
    // resetMessage("error", "网络连接失败...");
    throttle(() => {
      message.error("网络连接失败...");
    }, 1000);
    return Promise.reject(obj);
  }
  // 重试次数记录
  config.__retryCount += 1;
  let retryPromise = new Promise(function (resolve) {
    setTimeout(function () {
      resolve();
    }, config.retryDelay || 1);
  });
  // Return the promise in which recalls axios to retry the request
  return retryPromise.then(function () {
    return instance(config);
  });
};
/* 请求拦截器 */
instance.interceptors.request.use(
  (config) => {
    if (!config?.mark) {
      loading.loadingOpent();
    }
    loaddingNumber++;
    const tokenId = sessionStorage.getItem("X-Access-Token"); //要注释回来
    /*    const tokenId =
      "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE3NDIxNTc4NjIsInVzZXJuYW1lIjoidGVzdF9hZG1pbiJ9.iZMrIgcqUYZzvUPxSnib3BTYom5PqM8_eLv1g8YAMt4";*/
    // 异常之后 config.data 会变成字符串 不需要再次拼接
    if (config.data instanceof FormData) {
      tokenId && (config.headers["X-Access-Token"] = tokenId);
      config.headers["Content-Type"] = "multipart/form-data; charset=UTF-8";
      config.data.append("token", tokenId);
    } else {
      tokenId && (config.headers["X-Access-Token"] = tokenId);
    }
    return config;
  },
  (error) => {
    return Promise.error(error);
  }
);

/* 响应拦截器 */
instance.interceptors.response.use(
  (response) => {
    loaddingNumber--;
    if (loaddingNumber === 0) {
      loading.loadingClose();
      if (
        response.data.code !== 200 &&
        response.data.code !== 0 &&
        response.data !== "success" &&
        !(response.data instanceof Blob)
      ) {
        message.error(response.data.message || "网络错误");
      }
    }
    return Promise.resolve(response.data);
  },
  (error) => {
    loaddingNumber--;
    if (loaddingNumber === 0) {
      loading.loadingClose();
    }
    return retryConnect(error);
  }
);
instance.all = axios.all;
instance.spread = axios.spread;
export default instance;
